package com.OnTimeTeam.OnTime;

import java.io.File;
import java.util.ArrayList;


import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class FileSystem extends Activity {
	
	protected PowerManager.WakeLock mWakeLock;
	
	private Toast confirmationToast;
	private TextView addressConfirmation;
	
	public File parent; // the current folder
	
	public ArrayList<File> filesArray; // array of files in parent folder
	public ArrayList<Boolean> playerArray;
	public ArrayList<Integer> durationsArray;
	
	
	private File[] files;
	public static String chosenAudioFilePath;
	
	private int previousAudio;
	
	private ListView contentLV; //the list view of files
	public FilesContentAdapter fileContentAdapter; //Adapter for vibration LV	
	public TextView currentPath;
	private TextView audioFileName;
	//private Button cancel;
	private Button set;
	private MediaPlayer mMediaPlayer; 
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.file_system);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.files_title);
		
		//acquire the wakeLock
		acquireWakeLock();
		
        //Set the most far parent
		parent = this.getApplicationContext().getFilesDir();
		while(parent.getParentFile() != null)
			parent = parent.getParentFile();
		
		//Set list of files that in the parent
		files = parent.listFiles();
		for(int i = 0; i < files.length; ++i) {
			if(files[i].getName().equals("mnt")) {
				parent = files[i];
				break;
			}
		}
		
		//Initial initialization
		audioFileName = (TextView)findViewById(R.id.audioFileName);
		currentPath = (TextView)findViewById(R.id.path);
		set = (Button)findViewById(R.id.set);
		contentLV = (ListView)findViewById(R.id.filesList);
		mMediaPlayer = new MediaPlayer();
		
		final LayoutInflater inflater = (LayoutInflater) FileSystem.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View toastView = inflater.inflate(R.layout.costum_toast, (ViewGroup) findViewById(R.id.toast_layout_root));
		addressConfirmation = (TextView)toastView.findViewById(R.id.addressConfirmation);
		addressConfirmation.setTextColor(Color.parseColor("#CC0000"));
		addressConfirmation.setText(getResources().getString(R.string.filesError));
		
		confirmationToast = new Toast(getApplicationContext());
		confirmationToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		confirmationToast.setView(toastView);
		confirmationToast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 150);
		confirmationToast.setDuration(Toast.LENGTH_SHORT);
		
		
		//Initial set:
		if(chosenAudioFilePath != null)
			audioFileName.setText(chosenAudioFilePath);
		currentPath.setText(parent.getPath());
		set.setText(getResources().getString(R.string.choose));
		
		
		
		set.setOnClickListener(new Button.OnClickListener() {  
			public void onClick(View v) {
				
				Intent returnIntent = new Intent();
				returnIntent.putExtra("filePath", chosenAudioFilePath);
				setResult(RESULT_OK, returnIntent);     
				finish();
			}
		});
		

		//Init' arrays.
		filesArray = new ArrayList<File>();
		playerArray = new ArrayList<Boolean>();
		durationsArray = new ArrayList<Integer>();
		previousAudio = -1;
		
		setFilesArray();
		
		//init' adapter for the list-view, set the adapter for the files list-view
		fileContentAdapter = new FilesContentAdapter(FileSystem.this, R.layout.file_line, filesArray, playerArray, durationsArray);
		contentLV.setAdapter(fileContentAdapter);
		
		//Define what happens when clicking an item in the List-View
		contentLV.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {
				
				if(mMediaPlayer.isPlaying())
					mMediaPlayer.stop();
				
				//If the file is DIR - Refresh the list
				if(filesArray.get(index).isDirectory()) {
					
					FilesSystemAsyncTask fa = new FilesSystemAsyncTask(FileSystem.this, confirmationToast , filesArray.get(index));
					fa.execute();
					
				}
				else {
					
					audioFileName.setText(filesArray.get(index).getName());
					
					
					if((previousAudio != -1) && (previousAudio != index))
						if(playerArray.get(previousAudio))//if previous still on
							playerArray.set(previousAudio, false); //turn previous off
					
					if(playerArray.get(index))
						playerArray.set(index, false);
					else { //media isn't played
						playerArray.set(index, true);
						
						chosenAudioFilePath = filesArray.get(index).getAbsolutePath();
						
						try {
							mMediaPlayer = new MediaPlayer();
							mMediaPlayer.setDataSource(chosenAudioFilePath);
							mMediaPlayer.prepare();
							mMediaPlayer.start();
							
							
						} catch (Exception e) {}
						
						previousAudio = index;
						
					}
					
					fileContentAdapter.notifyDataSetChanged();
				}
			}
		});
	}
	
	public boolean setFilesArray() {
		
		//Get all files in folder
		files = parent.listFiles();
		
		for(int i = 0; i < files.length && i < 120; ++i){
			if(files[i].isDirectory()) {
				
				if(parent.getName().equals("mnt")) {
					if( (files[i].getName().equals("sdcard")) || (files[i].getName().equals("extSdCard")) ) {
						
						filesArray.add(files[i]);
						playerArray.add(false);
						durationsArray.add(0);
					}
				}
				else {
					filesArray.add(files[i]);	
					playerArray.add(false);
					durationsArray.add(0);
				}
			}
			else { // is File
				
				String extension = "";

				int ind = files[i].getName().lastIndexOf('.');
				if (ind > 0)
				    extension = files[i].getName().substring(ind+1);
				
				if(!extension.equals("") && 
						( (extension.equals("mp3")) 
								|| (extension.equals("wav")) 
								|| (extension.equals("wma")) )) {

					try {
						
						MediaPlayer tmpMP = new MediaPlayer();
						tmpMP.setDataSource(files[i].getAbsolutePath());
						tmpMP.prepare();
						durationsArray.add(tmpMP.getDuration());
						
						filesArray.add(files[i]);
						playerArray.add(false);
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				
			}
		}
		
		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if(mMediaPlayer.isPlaying())
			mMediaPlayer.stop();
		
		if (requestCode == 1) {

			Intent returnIntent = new Intent();
			
			if(resultCode == RESULT_OK){
				returnIntent.putExtra("filePath", data.getExtras().getString("filePath"));
				setResult(RESULT_OK, returnIntent);   
			}
			else {
				setResult(RESULT_CANCELED, returnIntent);        
			}
			
			finish();
		}
		
	}//onActivityResult
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		stopAllAffairs();
	}

	@Override
	protected void onStop() {
		super.onStop();
		
		stopAllAffairs();
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		stopAllAffairs();
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		//Acquire wakeLock
		acquireWakeLock();
	}

	@Override
	public void onBackPressed() {
		
		if(mMediaPlayer.isPlaying())
			mMediaPlayer.stop();
		
		if(parent.getName().equals("mnt")) {
			Intent returnIntent = new Intent();
			returnIntent.putExtra("filePath", chosenAudioFilePath);
			setResult(RESULT_OK, returnIntent); 

			finish();
		}
		else {
			FilesSystemAsyncTask fa = new FilesSystemAsyncTask(FileSystem.this, confirmationToast , parent.getParentFile());
			fa.execute();
		}
	}
	
	private void stopAllAffairs(){
		try{this.mWakeLock.release();}catch(Exception e){}
		if(mMediaPlayer.isPlaying())
			mMediaPlayer.stop();
	}
	
	private void acquireWakeLock(){
		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();
	}
	
	public boolean refreshList(File newParent){

		//Set new parent
		parent = newParent;
		
		//Remove all files from arrays
		filesArray.clear();
		playerArray.clear();
		durationsArray.clear();
		
		//Set array of files
		setFilesArray();
		
		
		return true;
	}
	
	public void updateViewAfterRefresh(){
		currentPath.setText(parent.getPath());
		fileContentAdapter.setItems(filesArray, playerArray, durationsArray);
	}
}
